<template>
	<div class="work-center-container">
		<!-- 顶部导航栏 -->
		<header class="work-center-header">
			<h1 class="header-title">选择工作中心</h1>
			<p class="header-desc">请选择您要操作的工作中心</p>
		</header>

		<tm-message ref="toast"></tm-message>
		<!-- 主要内容区域 -->
		<main class="work-center-content">
			<div class="center-grid">
				<!-- 工作中心卡片 - 循环渲染 -->
				<div v-for="(center, index) in workCenters" :key="index" @click="selectWorkCenter(index)"
					class="center-card">
					<!-- 卡片背景装饰 -->
					<div class="card-bg"></div>

					<!-- 卡片内容 -->
					<div class="card-content">
						<!-- 自定义图标（用CSS实现基础图标） -->
						<div class="card-icon" :class="`icon-${center.iconType}`"></div>
						<h3 class="card-title">{{ center.name }}</h3>
						<p class="card-desc">{{ center.code }}</p>

						<!-- 选中状态指示 -->
						<div class="card-check" v-if="selectedIndex === index">✓</div>
					</div>
				</div>
			</div>
		</main>
		<view style="height:100px"></view>
		<view class="report-modal" v-if="showReportModal">
			<view class="modal-mask" @click="closeReportModal"></view>
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">填写报工数量</text>
					<text class="modal-close" @click="closeReportModal">×</text>
				</view>

				<view class="modal-body">
					<!-- 任务单信息 -->
					<view class="modal-info">
						<text class="info-text">{{ currentOrder.material_idObject
		.name }}</text>
						<text class="info-subtext">计划数量: {{ currentOrder.production_quantity }} 件</text>
					</view>

					<view class="select-group">
						<text class="select-label">工序</text>
						<view class="select-wrapper">
							<picker mode="selector" :range="processList" :range-key="'name'"
								v-model="selectedProcessIndex" @change="handleProcessChange">
								<view class="picker-view">
									<text v-if="selectedProcess">{{ selectedProcess.name }}</text>
									<text v-else class="picker-placeholder">请选择工序</text>
								</view>
							</picker>
						</view>
					</view>

					<view class="select-group">
						<text class="select-label">操作人 *</text>
						<view class="select-wrapper">
							<picker mode="selector" :range="operatorList" :range-key="'real_name'"
								v-model="selectedOperatorIndex" @change="handleOperatorChange">
								<view class="picker-view">
									<text v-if="selectedOperator">{{ selectedOperator.real_name }}</text>
									<text v-else class="picker-placeholder">请选择操作人</text>
								</view>
							</picker>
						</view>
						<text class="error-hint" v-if="operatorError">{{ operatorError }}</text>
					</view>

					<!-- 数量输入 -->
					<view class="input-group">
						<text class="input-label">合格数量 *</text>
						<view class="input-wrapper">
							<input type="number" v-model="qualifiedQuantity" class="quantity-input"
								placeholder="请输入合格数量" @input="validateInput" ref="focusInput">
							<text class="input-unit">件</text>
						</view>
						<text class="error-hint" v-if="qualifiedError">{{ qualifiedError }}</text>
					</view>

					<view class="input-group">
						<text class="input-label">不合格数量</text>
						<view class="input-wrapper">
							<input type="number" v-model="unqualifiedQuantity" class="quantity-input"
								placeholder="请输入不合格数量" @input="validateInput">
							<text class="input-unit">件</text>
						</view>
					</view>

					<view class="total-row" v-if="totalQuantity > 0">
						<text class="total-label">合计数量:</text>
						<text class="total-value">{{ totalQuantity }} 件</text>
						<text class="total-warning" v-if="totalExceed">（超过计划数量）</text>
					</view>
				</view>

				<view class="modal-footer">
					<button class="submit-btn" :disabled="!canSubmit || isSubmitting" @click="submitReport">
						<template v-if="!isSubmitting">确认报工</template>
						<template v-if="isSubmitting">
							<view class="btn-spinner"></view>
							<text>提交中...</text>
						</template>
					</button>
				</view>
			</view>

		</view>

		<!-- 底部操作栏 -->
		<footer class="work-center-footer">
			<button @click="handleScan" class="confirm-btn">
				扫码报工
				<!-- <span class="btn-arrow">
					
				</span> -->
			</button>
		</footer>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				// 工作中心数据（iconType对应自定义CSS图标类型）
				workCenters: [],
				workOrders: [],
				// 选中的工作中心索引
				showReportModal: false,
				currentIndex: 0,
				processList: [],
				operatorList: [],
				selectedIndex: null,
				selectedOperator: null, // 选中的操作人对象
				qualifiedQuantity: '',
				unqualifiedQuantity: '0',
				canSubmit: false,
				operatorError: '', // 操作人选择错误提示
				currentOrder: null,
				isLoadingData: false,
				taskCode: '', //任务单编号
				// 提交状态
				isSubmitting: false,
				qualifiedError: '',
				showSuccess: false,
				selectedProcessIndex: -1, // 选中的工序索引
				selectedOperatorIndex: -1, // 选中的操作人索引
				selectedProcess: null, // 选中的工序对象
				taskCodeGx: "",
				targetTypes: ['industry', 'warehouse', 'flask', 'building', 'service'],
			};
		},
		computed: {
			// 计算合计数量
			totalQuantity() {
				const qualified = parseInt(this.qualifiedQuantity) || 0;
				const unqualified = parseInt(this.unqualifiedQuantity) || 0;
				return qualified + unqualified;
			}
		},
		created() {
			if(uni.getStorageSync('info')){
				this.selectedOperator = uni.getStorageSync('info')
				this.selectedOperator.real_name = uni.getStorageSync('info').realName
			}
			this.getWorkCenter()
		},
		methods: {
			//请求工作中心
			async getWorkCenter() {
				const res = await uni.$tm.request.post('app/base/form/working_center/page', {
					"keyword": "",
					"condition": [],
					"_is_deleted_": false,
					"page": 1,
					"limit": 50,
					"order": "desc"
				})

				this.workCenters = res.data.list
				this.workCenters.map(itm => itm.iconType = this.targetTypes[Math.floor(Math.random() * this.targetTypes
					.length)])

			},
			async submitReport() {
				if (!this.canSubmit || !this.currentOrder) return;
				var that = this
				this.isSubmitting = true;
				// 构造报工数据
				const reportData = {
					taskOrderId: this.currentOrder.id,
					processId: this.selectedProcess?.id,
					qualifiedQuantity: parseInt(this.qualifiedQuantity),
					unqualifiedQuantity: parseInt(this.unqualifiedQuantity),
					reportUserId: this.selectedOperator.id
				};
				return 
				try {
					const res = await uni.$tm.request.post(
						'/custom/order/taskOrder/report',
						reportData
					);
					if (res.code === 0) {
						// 报工成功处理
						this.$nextTick(() => {
							this.$refs.toast.show({
								model: 'success',
								label: '报工成功'
							})
						})
					} else {
						this.$nextTick(() => {
							this.$refs.toast.show({
								model: 'error',
								label: res.msg
							})
						})
					}
					// 关闭弹窗并重置状态
					this.closeReportModal();
				} catch {
					this.$nextTick(() => {
						this.$refs.toast.show({
							model: 'error',
							label: '请联系管理员'
						})
					})
				} finally {
					// 无论成功失败，都结束提交状态
					this.isSubmitting = false;
					this.closeReportModal()
				}

			},
			// 关闭报工弹窗
			closeReportModal() {
				this.selectedIndex = null
				this.currentOrder = null
				this.qualifiedQuantity = ''
				this.unqualifiedQuantity = '0'
				this.qualifiedError = ''
				this.totalExceed = false
				this.canSubmit = false
				this.selectedProcess = null
				this.showReportModal = false;
				this.selectedOperatorIndex = -1;
				this.processList = [];
				this.operatorList = [];
				this.taskCode = ""
				this.taskCodeGx = ""
			},
			// 选择工作中心
			selectWorkCenter(index) {
				const selectedCenter = this.workCenters[index];
				// 	// 实际项目中可替换为路由跳转或API请求
				uni.navigateTo({
					url: "/pages/gangben/workCenters?centerData=" + JSON.stringify(selectedCenter)
				})
			},
			//点击扫码按钮触发手机扫码
			// 1. 扫【报工码】搜索的时候要将后面的工序编码去做查找 将数据填到工序 同时要请求 openReportModal() 退出的时候 清空状态 重新做页面请求
			// 2. 扫【任务单编号】不做请求 同时要请求 openReportModal()  退出的时候 清空状态 重新做页面请求
			handleScan() {
				this.closeReportModal()
				uni.scanCode({
					onlyFromCamera: true, // 只允许从相机扫码
					scanType: ['barCode', 'qrCode'], // 支持的扫码类型
					success: (res) => {
						if (res.result) {
							//扫出来是携带工序的
							if (res.result.split("||").length == 2) {
								this.taskCode = res.result.split("||")[0]
								this.taskCodeGx = res.result.split("||")[1]
							} else {
								this.taskCode = res.result
							}
							this.searchSuccessPopup();
						}
					},
					fail: (err) => {
						// 显示错误提示
						if (err.errMsg !== 'scanCode:fail cancel') { // 排除用户主动取消的情况
							this.$nextTick(() => {
								this.$refs.toast.show({
									model: 'error',
									label: '扫码失败，请重试'
								})
							})
						}
					}
				});
			},
			validateInput() {
				// 重置错误提示
				this.operatorError = '';
				this.qualifiedError = '';
				this.totalExceed = false;
				this.canSubmit = false;

				// 2. 验证操作人选择
				if (!this.selectedOperator) {
					this.operatorError = '请选择操作人'; 	
					return;
				}

				// 3. 验证合格数量
				const qualified = parseInt(this.qualifiedQuantity) || 0;
				if (isNaN(qualified) || qualified <= 0) {
					this.qualifiedError = '合格数量必须大于0';
					return;
				}

				// 4. 验证合计数量
				const unqualified = parseInt(this.unqualifiedQuantity) || 0;
				if (qualified + unqualified > this.currentOrder.planQuantity) {
					this.totalExceed = true;
					return;
				}

				// 所有验证通过
				this.canSubmit = true;
			},
			handleProcessChange(e) {
				const index = e.detail.value;
				this.selectedProcessIndex = index;
				this.selectedProcess = this.processList[index];
				console.log(this.selectedProcess)
				this.validateInput(); // 重新验证
			},
			handleOperatorChange(e) {
				const index = e.detail.value;
				this.selectedOperatorIndex = index;
				this.selectedOperator = this.operatorList[index];
				this.validateInput(); // 重新验证
			},
			//搜索成功后弹窗
			async searchSuccessPopup() {
				var that = this
				const res = await uni.$tm.request.post('app/production/form/task_order/page', {
					"keyword": "",
					"condition": [{
						"connect": "OR",
						"fieldName": "code",
						"type": "eq",
						"value": this.taskCode
					}],
					"_is_deleted_": false,
					"page": 1,
					"limit": 50,
					"order": "desc"
				})
				if (res.code === 0 && res.data) {
					this.workOrders = res.data.list || [];
					if (this.workOrders.length == 1) {
						this.currentOrder = this.workOrders[0]
						this.currentIndex = 0

						if (this.taskCodeGx) {
							try {
								const processRes = await uni.$tm.request.post(
									'/custom/order/productionOrder/idToprocessInfo', {
										processId: this.taskCodeGx
									}
								)
								// 处理请求成功的逻辑
								if (processRes.code === 0) {
									this.selectedProcess = processRes.data
									this.selectedProcessIndex = 0
								}
							} catch (error) {
								console.error('请求发生错误', error)
							}
						}
						this.getAllData()
						that.showReportModal = true
					}
				} else {
					this.$nextTick(() => {
						this.$refs.toast.show({
							model: 'error',
							label: '数据加载失败'
						})
					})
					this.workOrders = [];
				}
			},
			async fetchProcessData(orderId) {

				const res = await uni.$tm.request.post('app/production/form/task_order_process/page', {
					"keyword": "",
					"condition": [{
						"fieldName": "task_id",
						"connect": "OR",
						"type": "eq",
						"value": orderId,
						"other": true
					}],
					"_is_deleted_": false,
					"page": 1,
					"limit": 50,
					"order": "desc"
				})
				if (res.code === 0 && res.data && res.data.list) {
					res.data.list.map(itm => {
						return itm.name = itm.process_idObject.name + " (" + itm.process_idObject
							.code + ")"
					})
					return res.data.list;
				} else {
					return []
				}
			},
			// 获取操作人数据
			async fetchOperatorData() {
				// 模拟API请求
				const res = await uni.$tm.request.post('app/sys/form/user/page', {
					"keyword": "",
					"condition": [],
					"_is_deleted_": false,
					"page": 1,
					"limit": 999,
					"order": "desc"
				})
				if (res.code === 0 && res.data && res.data.list) {
					return res.data.list;
				} else {
					return []
				}
			},
			// 工序选择变化
			getAllData() {
				var that = this
				// 弹窗打开后让合格数量输入框获取焦点
				this.isLoadingData = true;
				Promise.all([
					this.fetchProcessData(this.currentOrder.id), // 根据任务单ID获取工序
					this.fetchOperatorData() // 获取操作人列表
				]).then(([processData, operatorData]) => {
					this.processList = processData;
					this.operatorList = operatorData;
				}).catch(err => {
					that.$nextTick(() => {
						that.$refs.toast.show({
							model: 'error',
							label: '数据加载失败'
						})
					})

				}).finally(() => {
					this.isLoadingData = false;
				});
			},
		}
	};
</script>

<style scoped>
	/* 基础容器样式 */
	.work-center-container {
		min-height: 100vh;
		background: linear-gradient(to bottom, #f0f7ff, #ffffff);
		display: flex;
		flex-direction: column;
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
	}

	.btn-arrow svg {
		width: 20px;
		height: 20px;
		color: #000;
		/* 图标颜色 */
	}

	/* 顶部导航栏 */
	.work-center-header {
		padding: 18px 20px;
		background: rgba(255, 255, 255, 0.8);
		backdrop-filter: blur(8px);
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		text-align: center;
	}

	.header-title {
		font-size: 22px;
		font-weight: 600;
		color: #1e293b;
		margin: 0 0 6px;
	}

	.header-desc {
		font-size: 14px;
		color: #64748b;
		margin: 0;
	}

	/* 主要内容区域 */
	.work-center-content {
		flex: 1;
		padding: 20px;
		overflow-y: auto;
	}
	

	/* 卡片网格布局 */
	.center-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 16px;
	}

	/* 工作中心卡片 */
	.center-card {
		position: relative;
		background: #ffffff;
		border-radius: 20px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		overflow: hidden;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.center-card:hover {
		transform: translateY(-4px);
		box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
	}

	.center-card--selected {
		border: 2px solid #3b82f6;
		animation: pulse 0.5s ease-in-out;
	}

	/* 卡片背景装饰 */
	.card-bg {
		position: absolute;
		top: 0;
		right: 0;
		width: 80px;
		height: 80px;
		background: rgba(59, 130, 246, 0.1);
		border-radius: 50%;
		transform: translate(40%, -40%);
		transition: transform 0.5s ease;
	}

	.center-card:hover .card-bg {
		transform: translate(40%, -40%) scale(1.5);
	}

	/* 卡片内容 */
	.card-content {
		position: relative;
		padding: 20px;
		z-index: 1;
	}

	/* 自定义CSS图标 */
	.card-icon {
		width: 48px;
		height: 48px;
		border-radius: 12px;
		background: rgba(59, 130, 246, 0.1);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 12px;
		color: #3b82f6;
		font-size: 24px;
		transition: all 0.3s ease;
	}

	.center-card:hover .card-icon {
		background: #3b82f6;
		color: #ffffff;
	}

	/* 图标具体样式（模拟不同类型图标） */
	.icon-industry::before {
		content: "🏭";
	}

	.icon-check::before {
		content: "✅";
	}

	.icon-warehouse::before {
		content: "🏬";
	}

	.icon-flask::before {
		content: "🔬";
	}

	.icon-building::before {
		content: "🏢";
	}

	.icon-service::before {
		content: "📞";
	}

	/* 卡片文字 */
	.card-title {
		font-size: 16px;
		font-weight: 600;
		color: #1e293b;
		margin: 0 0 6px;
	}

	.card-desc {
		font-size: 12px;
		color: #64748b;
		margin: 0;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	/* 选中状态指示 */
	.card-check {
		position: absolute;
		bottom: -8px;
		right: -8px;
		width: 24px;
		height: 24px;
		background: #3b82f6;
		color: #ffffff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		font-weight: bold;
	}

	/* 底部操作栏 */
	.work-center-footer {
		position: fixed;
		width:100%;
		bottom:0;
		z-index:99;
		padding: 16px 20px;
		background: rgba(255, 255, 255, 0.8);
		backdrop-filter: blur(8px);
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
	}

	/* 确认按钮 */
	.confirm-btn {
		width: 100%;
		padding: 14px;
		background: #3b82f6;
		color: #ffffff;
		border: none;
		border-radius: 12px;
		font-size: 16px;
		font-weight: 600;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
	}

	.confirm-btn:hover {
		background: #2563eb;
		box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
	}

	.confirm-btn--disabled {
		background: #e2e8f0;
		color: #94a3b8;
		cursor: not-allowed;
		box-shadow: none;
	}

	.btn-arrow {
		margin-left: 8px;
		font-size: 18px;
	}

	/* 动画效果 */
	@keyframes pulse {

		0%,
		100% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.05);
		}
	}

	/* 响应式适配（确保手机端显示正常） */
	@media (max-width: 375px) {
		.center-grid {
			gap: 12px;
		}

		.card-content {
			padding: 16px;
		}

		.card-icon {
			width: 40px;
			height: 40px;
			font-size: 20px;
		}

		.confirm-btn {
			padding: 12px;
			font-size: 15px;
		}
	}

	.report-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.modal-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.modal-content {
		width: 90%;
		max-width: 360px;
		background-color: #ffffff;
		border-radius: 16px;
		position: relative;
		z-index: 10;
		box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
	}

	.modal-header {
		padding: 16px 20px;
		border-bottom: 1px solid #f5f5f5;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.modal-title {
		font-size: 18px;
		font-weight: 600;
		color: #1e293b;
	}

	.modal-close {
		font-size: 20px;
		color: #64748b;
		cursor: pointer;
	}

	.modal-body {
		padding: 10px 20px;
	}

	.modal-info {
		margin-bottom: 10px;
		padding-bottom: 8px;
		border-bottom: 1px solid #f5f5f5;
	}

	.info-text {
		font-size: 16px;
		font-weight: 500;
		color: #1e293b;
		display: block;
		margin-bottom: 4px;
	}

	.info-subtext {
		font-size: 14px;
		color: #64748b;
	}

	/* 弹窗输入样式 */
	.input-group {
		margin-bottom: 16px;
	}

	.input-label {
		font-size: 14px;
		color: #475569;
		display: block;
		margin-bottom: 8px;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		border: 1px solid #e2e8f0;
		border-radius: 8px;
		padding: 0 12px;
		height: 44px;
	}

	.input-wrapper:focus-within {
		border-color: #3b82f6;
	}

	.quantity-input {
		flex: 1;
		height: 100%;
		font-size: 16px;
		border: none;
		outline: none;
		padding: 0;
	}

	.input-unit {
		font-size: 16px;
		color: #64748b;
		padding-left: 8px;
	}

	.error-hint {
		font-size: 12px;
		color: #ef4444;
		margin-top: 6px;
		display: block;
	}

	.total-row {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 6px 0;
	}

	.total-label {
		font-size: 14px;
		color: #64748b;
		margin-right: 8px;
	}

	.total-value {
		font-size: 14px;
		color: #1e293b;
		font-weight: 600;
	}

	.total-warning {
		font-size: 12px;
		color: #ef4444;
		margin-left: 8px;
	}

	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.modal-footer {
		padding: 16px 20px;
		border-top: 1px solid #f5f5f5;
	}

	.select-group {
		margin-bottom: 16px;
	}

	.select-label {
		font-size: 14px;
		color: #475569;
		display: block;
		margin-bottom: 8px;
	}

	.select-wrapper {
		border: 1px solid #e2e8f0;
		border-radius: 8px;
		overflow: hidden;
	}

	.picker-view {
		padding: 0 12px;
		height: 44px;
		display: flex;
		align-items: center;
		font-size: 16px;
		color: #1e293b;
	}

	.picker-placeholder {
		color: #94a3b8;
	}

	/* 页面容器 */
	.work-order-container {
		min-height: 100vh;
		padding-bottom: 80px;
		box-sizing: border-box;
		background-color: #f5f7fa;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}

	/* 顶部导航 */
	.page-header {
		padding: 20px 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #eee;
	}

	.header-title {
		font-size: 18px;
		font-weight: 600;
		color: #1e293b;
		display: block;
	}





	.submit-btn {
		width: 100%;
		padding: 14px;
		background-color: #3b82f6;
		color: #ffffff;
		border: none;
		border-radius: 8px;
		font-size: 16px;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.submit-btn:disabled {
		background-color: #e2e8f0;
		color: #94a3b8;
	}

	.btn-spinner {
		width: 16px;
		height: 16px;
		border: 2px solid #ffffff;
		border-top-color: transparent;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-right: 8px;
	}

	/* 成功提示 */
	.success-toast {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(16, 185, 129, 0.9);
		color: #ffffff;
		padding: 16px 24px;
		border-radius: 8px;
		display: flex;
		align-items: center;
		z-index: 1000;
		animation: fadeInOut 2s;
	}

	.toast-icon {
		font-size: 20px;
		margin-right: 8px;
	}

	.toast-text {
		font-size: 16px;
		font-weight: 500;
	}
</style>